package freecomm.study.notes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class NotesActivity extends Activity
{
    class dropItem extends AsyncTask<Integer, Void, Boolean>
    {

        @Override
        protected Boolean doInBackground(Integer... params)
        {
            // TODO Auto-generated method stub
            noteDatabaseHelper.delete(params[0]);
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result)
        {
            // TODO Auto-generated method stub
            if (result)
            {
                Toast.makeText(NotesActivity.this, "删除成功", Toast.LENGTH_SHORT)
                        .show();

            } else
            {

                Toast.makeText(NotesActivity.this, "删除失败", Toast.LENGTH_SHORT)
                        .show();
            }
            notesGridAdapter.notifyDataSetChanged();
            notesListAdapter.notifyDataSetChanged();
            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute()
        {
            // TODO Auto-generated method stub
            Toast.makeText(NotesActivity.this, "正在删除", Toast.LENGTH_SHORT);
            notesDataList.remove(selectedItemPosition);
            super.onPreExecute();
        }

    }

    class initMainActivity extends AsyncTask<Void, Void, Cursor>
    {

        @Override
        protected Cursor doInBackground(Void... params)
        {
            Cursor mCursor = noteDatabaseHelper.query();
            return mCursor;
        }

        @Override
        protected void onPostExecute(Cursor result)
        {
            // TODO Auto-generated method stub
            if (0 == result.getCount())
            {
                readingDatabaseTextView.setVisibility(View.GONE);
                noNoteImageView.setVisibility(View.VISIBLE);
                brushButton.setTag(0);
                brushButton.setBackgroundResource(R.drawable.btn_view_disable);
            } else
            {
                readingDatabaseTextView.setVisibility(View.GONE);
                notesDataList.removeAll(notesDataList);
                result.moveToLast();
                Map<String, Object> mDataMap;
                for (int i = 0; i < result.getCount(); i++)
                {
                    mDataMap = new HashMap<String, Object>();
                    String mContent = result
                            .getString(DATABASE_COL_MAP_CONTENT);
                    if (mContent.length() > 15)
                    {
                        mContent = mContent.substring(0, 15);
                        mContent += "...";
                    }
                    mDataMap.put(LIST_DATA_MAP_ID,
                            result.getInt(DATABASE_COL_MAP_ID));
                    mDataMap.put(LIST_DATA_MAP_KEY_CONTENT, mContent);
                    mDataMap.put(LIST_DATA_MAP_KEY_COLOR,
                            result.getInt(DATABASE_COL_MAP_COLOR));
                    result.moveToPrevious();
                    notesDataList.add(mDataMap);
                }
                String brushStat = preferenceReader.getString(
                        PREFERENCE_BRUSH_MAP_KEY_BRUSHSTAT, "");
                if (brushStat.equals(BRUSH_BTN_STAT_LIST)
                        || brushStat.isEmpty())// change to list
                {
                    changeToList();

                } else
                {
                    changeToGrid();
                }
            }
            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute()
        {
            // TODO Auto-generated method stub
            readingDatabaseTextView.setVisibility(View.VISIBLE);
            super.onPreExecute();
        }

    }

    class NoteSimpleAdapter extends SimpleAdapter
    {
        private List<Map<String, Object>> mData = new ArrayList<Map<String, Object>>();

        public NoteSimpleAdapter(Context context,

        List<? extends Map<String, ?>> data, int resource, String[] from,
                int[] to)
        {
            super(context, data, resource, from, to);
            // TODO Auto-generated constructor stub
            mData = (List<Map<String, Object>>) data;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            // TODO Auto-generated method stub
            View mView = super.getView(position, convertView, parent);
            RelativeLayout mRelativeLayout = (RelativeLayout) mView
                    .findViewById(R.id.bg_layout);
            switch (mData.get(position).get(LIST_DATA_MAP_KEY_COLOR).hashCode())
            {

            case BG_COLOR_ID_RED:
                mRelativeLayout
                        .setBackgroundResource(R.drawable.item_selector_red);
                break;
            case BG_COLOR_ID_PINK:
                mRelativeLayout
                        .setBackgroundResource(R.drawable.item_selector_pink);
                break;
            case BG_COLOR_ID_BLUE:
                mRelativeLayout
                        .setBackgroundResource(R.drawable.item_selector_blue);
                break;
            case BG_COLOR_ID_GREEN:
                mRelativeLayout
                        .setBackgroundResource(R.drawable.item_selector_green);
                break;
            default:
                mRelativeLayout
                        .setBackgroundResource(R.drawable.item_selector_yellow);
                break;
            }
            mRelativeLayout.setOnClickListener(noteItemClickListener);
            registerForContextMenu(mView);
            return mView;
        }

    }

    class sendSMS extends AsyncTask<Integer, Void, String>
    {

        @Override
        protected String doInBackground(Integer... params)
        {
            // TODO Auto-generated method stub
            Cursor mCursor = noteDatabaseHelper.query(params[0]);
            mCursor.moveToFirst();
            String mText = mCursor.getString(1);
            return mText;
        }

        @Override
        protected void onPostExecute(String result)
        {
            // TODO Auto-generated method stub
            Intent it = new Intent(Intent.ACTION_VIEW);
            it.putExtra("sms_body", result);
            it.setType("vnd.android-dir/mms-sms");
            startActivity(it);
        }

    }

    class OpenDB extends AsyncTask<Void, Void, Void>
    {

        @Override
        protected Void doInBackground(Void... params)
        {
            // TODO Auto-generated method stub
            noteDatabaseHelper = new NoteDatabaseHelper(getApplicationContext());
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            // TODO Auto-generated method stub
            setContentView(R.layout.notes);
            initComponents();
            regeistListeners();
            super.onPostExecute(result);
            new initMainActivity().execute();
        }
    }

    static final int BG_COLOR_ID_BLUE = 3;
    static final int BG_COLOR_ID_GREEN = 4;
    static final int BG_COLOR_ID_PINK = 2;
    static final int BG_COLOR_ID_RED = 1;
    static final int BG_COLOR_ID_YELLOW = 0;
    static final String BRUSH_BTN_STAT_DISABLE = "0";
    static final String BRUSH_BTN_STAT_GRID = "2";
    static final String BRUSH_BTN_STAT_LIST = "1";
    static final int DATABASE_COL_MAP_COLOR = 2;
    static final int DATABASE_COL_MAP_CONTENT = 1;
    static final int DATABASE_COL_MAP_ID = 0;
    static final int DATABASE_COL_MAP_TIME = 3;
    static final String LIST_DATA_MAP_ID = "id";
    static final String LIST_DATA_MAP_KEY_COLOR = "color";
    static final String LIST_DATA_MAP_KEY_CONTENT = "content";
    static private final int POPUP_MENU_ITEM_DELETE = Menu.FIRST + 101;
    static private final int POPUP_MENU_ITEM_EDIT = Menu.FIRST + 100;
    static private final int POPUP_MENU_ITEM_SHARE = Menu.FIRST + 102;
    static final String PREFERENCE_BRUSH_MAP_KEY_BRUSHSTAT = "brushstat";
    private Button brushButton;
    private OnClickListener brushButtonClickListener = new OnClickListener()
    {

        public void onClick(View v)
        {
            // TODO Auto-generated method stub

            if (brushButton.getTag().toString().equals(BRUSH_BTN_STAT_GRID))
            {
                changeToList();

            } else if (brushButton.getTag().toString()
                    .equals(BRUSH_BTN_STAT_LIST))
            {
                changeToGrid();
            }
            setHigherNewNoteButton();
        }
    };
    private long exitTime = 0;
    private OnTouchListener itemTouchListener = new OnTouchListener()
    {

        public boolean onTouch(View v, MotionEvent event)
        {
            // TODO Auto-generated method stub
            int last = ((AbsListView) v).getLastVisiblePosition();
            int count = ((AbsListView) v).getCount();
            if (last < count - 1)
            {
                setLowerNewNoteButton();
            }
            return false;
        }
    };
    private Button newNoteButton;
    private OnClickListener newNoteButtonClickListener = new OnClickListener()
    {

        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            Intent mIntent = new Intent(NotesActivity.this, EditNote.class);
            startActivity(mIntent);
            noteDatabaseHelper.close();
            finish();
        }
    };
    private ImageView noNoteImageView;
    private NoteDatabaseHelper noteDatabaseHelper;
    private OnClickListener noteItemClickListener = new OnClickListener()
    {

        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            if (brushButton.getTag() == BRUSH_BTN_STAT_GRID)
            {
                selectedItemPosition = notesGridView.getPositionForView(v);
            } else
            {
                selectedItemPosition = notesListView.getPositionForView(v);
            }
            int mId = Integer.parseInt(notesDataList.get(selectedItemPosition)
                    .get(LIST_DATA_MAP_ID).toString());
            Bundle data = new Bundle();
            data.putInt("id", mId);
            Intent intent = new Intent(NotesActivity.this, EditNote.class);
            intent.putExtras(data);
            noteDatabaseHelper.close();
            startActivity(intent);
            finish();
        }
    };
    private List<Map<String, Object>> notesDataList = new ArrayList<Map<String, Object>>();

    private NoteSimpleAdapter notesGridAdapter;

    private GridView notesGridView;

    private NoteSimpleAdapter notesListAdapter;
    private ListView notesListView;
    private SharedPreferences preferenceReader;
    private TextView readingDatabaseTextView;

    private int selectedItemPosition = -1;

    protected void changeToGrid()
    {
        notesGridAdapter.notifyDataSetChanged();
        notesListView.setVisibility(View.GONE);
        notesGridView.setVisibility(View.VISIBLE);
        brushButton.setTag(BRUSH_BTN_STAT_GRID);
        brushButton.setBackgroundResource(R.drawable.btn_view_list);
        preferenceReader
                .edit()
                .putString(PREFERENCE_BRUSH_MAP_KEY_BRUSHSTAT,
                        BRUSH_BTN_STAT_GRID).commit();
    }

    protected void changeToList()
    {
        notesListAdapter.notifyDataSetChanged();
        notesGridView.setVisibility(View.GONE);
        notesListView.setVisibility(View.VISIBLE);
        brushButton.setTag(BRUSH_BTN_STAT_LIST);
        brushButton.setBackgroundResource(R.drawable.btn_view_normal);
        preferenceReader
                .edit()
                .putString(PREFERENCE_BRUSH_MAP_KEY_BRUSHSTAT,
                        BRUSH_BTN_STAT_LIST).commit();
    }

    private void initComponents()
    {
        preferenceReader = getSharedPreferences("note", MODE_PRIVATE);
        brushButton = (Button) findViewById(R.id.brushButton);
        newNoteButton = (Button) findViewById(R.id.newNoteButton);
        noNoteImageView = (ImageView) findViewById(R.id.noNoteImageView);
        notesListView = (ListView) findViewById(R.id.notesListView);
        notesGridView = (GridView) findViewById(R.id.notesGridView);
        readingDatabaseTextView = (TextView) findViewById(R.id.readingDatabaseTextView);
        notesListAdapter = new NoteSimpleAdapter(this, notesDataList,
                R.layout.notes_list_item,
                new String[] { LIST_DATA_MAP_KEY_CONTENT },
                new int[] { R.id.notesItemTextView });
        notesListView.setAdapter(notesListAdapter);
        notesGridAdapter = new NoteSimpleAdapter(this, notesDataList,
                R.layout.notes_grid_item,
                new String[] { LIST_DATA_MAP_KEY_CONTENT },
                new int[] { R.id.notesItemTextView });
        notesGridView.setAdapter(notesGridAdapter);
        newNoteButton.requestFocus();
    }

    @Override
    public boolean onContextItemSelected(MenuItem item)
    {
        int mId = Integer.parseInt(notesDataList.get(selectedItemPosition)
                .get(LIST_DATA_MAP_ID).toString());
        switch (item.getItemId())
        {

        case POPUP_MENU_ITEM_EDIT:
            Bundle data = new Bundle();
            data.putInt("id", mId);
            Intent intent = new Intent(NotesActivity.this, EditNote.class);
            intent.putExtras(data);
            noteDatabaseHelper.close();
            startActivity(intent);
            finish();
            break;
        case POPUP_MENU_ITEM_DELETE:

            new dropItem().execute(mId);
            break;
        case POPUP_MENU_ITEM_SHARE:
            new sendSMS().execute(mId);
            break;

        }
        return true;
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        new OpenDB().execute();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo)
    {
        if (brushButton.getTag() == BRUSH_BTN_STAT_GRID)
        {
            selectedItemPosition = notesGridView.getPositionForView(v);
        } else
        {
            selectedItemPosition = notesListView.getPositionForView(v);
        }
        menu.setHeaderTitle(((TextView) v.findViewById(R.id.notesItemTextView))
                .getText());
        menu.add(0, POPUP_MENU_ITEM_EDIT, 0, "编辑");
        menu.add(0, POPUP_MENU_ITEM_DELETE, 0, "删除");
        menu.add(0, POPUP_MENU_ITEM_SHARE, 0, "发送");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if (event.getRepeatCount() == 0)
            {
                if ((System.currentTimeMillis() - exitTime) > 2000)
                {
                    Toast.makeText(this, "再按一次返回键退出程序", Toast.LENGTH_SHORT)
                            .show();
                    exitTime = System.currentTimeMillis();
                } else
                {
                    finish();
                    System.exit(0);
                }
                return true;
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void regeistListeners()
    {
        brushButton.setOnClickListener(brushButtonClickListener);
        newNoteButton.setOnClickListener(newNoteButtonClickListener);
        notesListView.setOnTouchListener(itemTouchListener);
        notesGridView.setOnTouchListener(itemTouchListener);
    }

    private void setHigherNewNoteButton()
    {
        RelativeLayout.LayoutParams params = (LayoutParams) newNoteButton
                .getLayoutParams();
        params.height = 200;
        newNoteButton.setLayoutParams(params);
    }

    private void setLowerNewNoteButton()
    {
        RelativeLayout.LayoutParams params = (LayoutParams) newNoteButton
                .getLayoutParams();
        params.height = 120;
        newNoteButton.setLayoutParams(params);
    }
}